<template>
  <view class="address-page">
    <view class="form">
      <view class="form-item">
        <view class="form-name">
          <input class="input" v-model="sForm.name" placeholder="姓名" />
        </view>
        <view class="form-phone">
          <input class="input" v-model="sForm.phone" placeholder="手机号" />
        </view>
      </view>
      <view class="form-item">
        <view class="form-selector">
          <picker
            class="selector"
            mode="multiSelector"
            name="area"
            :value="selectorValue"
            @columnchange="bindTypeColumnChange"
            @change="bindTypeChange"
            :range="selectorRange"
            range-key="areaName"
          >
            <view
              class="selector-input"
              :style="{ color: selectType ? '' : 'rgba(0,0,0,0.65)' }"
              >{{ selectType ? selectType.areaName.join(" ") : "请选择地区" }}
            </view>
            <image
              class="selectIcon"
              src="https://ltjt.sjzballsportpark.com/statics/tyc/static/selectIcon.png"
            ></image>
          </picker>
        </view>
      </view>
      <view class="form-item">
        <view class="form-address">
          <input
            type="text"
            name="name"
            v-model.trim="sForm.address"
            placeholder="详细地址"
          />
        </view>
      </view>
      <view class="form-item">
        <view class="form-radio" @click="changeDefault">
          <view class="radio" :class="{ active: sForm.isDefault }"></view>
          <view class="radio-text"> 设置为默认地址</view>
        </view>
      </view>
    </view>
    <view class="btn-box">
      <view class="btn-cancel" @click="isDeleOrCancel()">
        {{ id ? "删除" : "取消" }}</view
      >
      <view class="btn-confirm" @click="submitFun">保存</view>
    </view>
  </view>
</template>

<script>
import {
  addAddress,
  deleteAddress,
  editAddress,
  getAddressArea,
  getAddressDetail,
  getAddressNextAreaByCode,
} from "@/config/api.js";
import WxValidate from "@/utils/WxValidate";

export default {
  props: ["id"],
  data() {
    return {
      selectorRange: [],
      selectType: null,
      selectorValue: [0, 0, 0],
      WxValidate: null,
      detail: "",
      sForm: {
        name: null,
        phone: "",
        area: "",
        address: "",
        isDefault: false,
      },
    };
  },
  computed: {},
  onLoad(option) {
    if (option.id && option.id != "") {
      this.id = option.id;
      uni.setNavigationBarTitle({
        title: "编辑地址",
      });
      this.getDetail();
    }
    this.initValidate();
    this.getArea();
  },

  mounted() {},
  methods: {
    getDetail() {
      getAddressDetail({ _id: this.id })
        .then((res) => {
          console.log("getDetail====", res);
          if (res.code === 200) {
            this.detail = res.data;
            this.sForm = {
              name: res.data.name,
              phone: res.data.phone,
              address: res.data.address,
              isDefault: res.data.isDefault == "0" ? false : true,
            };
            this.selectType = {
              code: [res.data.province, res.data.city, res.data.county],
              areaName: [
                res.data.provinceName,
                res.data.cityName,
                res.data.countyName,
              ],
            };
            this.sForm.area = this.selectType.areaName;
          }
        })
        .catch((err) => console.log("错误了", err));
    },
    initValidate() {
      const rules = {
        name: { required: true },
        phone: { required: true, tel: true },
        area: { required: true },
        address: { required: true },
      };
      const message = {
        name: { required: "请输入姓名！" },
        phone: { required: "请输入手机号！", tel: "请输入正确的手机号！" },
        area: { required: "请选择地区" },
        address: { required: "请输入详细地址！" },
      };
      this.WxValidate = new WxValidate(rules, message);
    },
    getArea() {
      getAddressArea()
        .then((res) => {
          console.log("getDetail====", res);
          if (res.code === 200) {
            this.selectorRange = [
              res.data.level1,
              res.data.level2,
              res.data.level3,
            ];
          }
        })
        .catch((err) => console.log("错误了", err));
    },
    bindTypeChange(e) {
      const values = e.detail.value; // 获取选择器的值
      const province = this.selectorRange[0][values[0]];
      const city = this.selectorRange[1][values[1]];
      const area = this.selectorRange[2][values[2]];
      this.selectType = {
        code: [province.areaCode, city.areaCode, area.areaCode],
        areaName: [province.areaName, city.areaName, area.areaName],
      };
      this.sForm.area = this.selectType.areaName;
    },
    async bindTypeColumnChange(e) {
      const column = e.detail.column; // 改变的列索引
      const value = e.detail.value; // 改变的列的值
      // 判断改变的是省份列还是市列
      if (column === 0) {
        // 根据选择的省份设置市的选项
        let areaList = await getAddressNextAreaByCode({
          areaCode: this.selectorRange[0][value].areaCode,
        });
        const cities = areaList.data;
        this.$set(this.selectorRange, 1, cities);
        // 重置市的选中值
        this.$set(this.selectorValue, 1, 0);
        let areaList2 = await getAddressNextAreaByCode({
          areaCode: this.selectorRange[1][0].areaCode,
        });
        const areas = areaList2.data;
        this.$set(this.selectorRange, 2, areas);
        // 重置区的选中值
        this.$set(this.selectorValue, 2, 0);
      } else if (column === 1) {
        // 根据选择的市设置区的选项
        let areaList = await getAddressNextAreaByCode({
          areaCode: this.selectorRange[1][value].areaCode,
        });
        const areas = areaList.data;
        this.$set(this.selectorRange, 2, areas);
        // 重置区的选中值
        this.$set(this.selectorValue, 2, 0);
      }
    },
    deleteFun() {
      deleteAddress({ _id: this.id })
        .then((res) => {
          console.log("deleteFun====", res);
          if (res.code === 200) {
            this.toURL("", {}, { type: "back" });
          }
        })
        .catch((err) => console.log("错误了", err));
    },
    changeDefault() {
      this.sForm.isDefault = !this.sForm.isDefault;
    },
    submitFun() {
      const isValidate = this.WxValidate.checkForm(this.sForm);
      if (!isValidate) {
        const errorList = this.WxValidate.errorList;
        uni.showToast({ title: errorList[0].msg, icon: "none" });
        return false;
      }
      const areaList = {
        province: this.selectType.code[0],
        provinceName: this.selectType.areaName[0],
        city: this.selectType.code[1],
        cityName: this.selectType.areaName[1],
        county: this.selectType.code[2],
        countyName: this.selectType.areaName[2],
      };
      let params = {
        ...this.sForm,
        isDefault: this.sForm.isDefault ? 1 : 0,
        ...areaList,
      };
      if (this.id) params = { ...params, id: this.id };
      if (this.id) {
        editAddress({ ...this.detail, ...params }).then((res) => {
          uni.hideLoading();
          if (res.code === 200) {
            uni.showToast({ title: "操作成功！", icon: "none" });
            this.toURL("", {}, { type: "back" });
          } else {
            uni.showToast({ title: res.msg || "操作失败！", icon: "none" });
          }
        });
      } else {
        addAddress({ ...params }).then((res) => {
          uni.hideLoading();
          if (res.code === 200) {
            uni.showToast({ title: "操作成功！" });
            this.toURL("", {}, { type: "back" });
          } else {
            uni.showToast({ title: res.msg || "操作失败！", icon: "none" });
          }
        });
      }
    },
    isDeleOrCancel() {
      if (this.id) {
        this.deleteFun();
      } else {
        this.toURL("", {}, { type: "back" });
      }
    },
  },
};
</script>

<style lang="scss">
.address-page {
  .form {
    padding: 48rpx 32rpx 0;
  }

  .form-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 96rpx;
    margin-bottom: 24rpx;

    input {
      height: 96rpx;
      padding: 0 24rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
      line-height: 96rpx;
    }
  }

  .form-name {
    width: 256rpx;
    height: 96rpx;
    margin-right: 16rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  .form-phone {
    width: 406rpx;
    height: 96rpx;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  .form-selector {
    position: relative;
    height: 96rpx;
    width: 100%;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  .selector-input {
    height: 96rpx;
    line-height: 96rpx;
    padding: 0 24rpx;
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.9);
  }

  .selectIcon {
    position: absolute;
    top: 24rpx;
    right: 24rpx;
    width: 32rpx;
    height: 32rpx;
  }

  .form-address {
    width: 100%;
    background: #ffffff;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 1px solid rgba(0, 0, 0, 0.2);
  }

  .form-radio {
    display: flex;
    align-items: center;

    .radio {
      width: 40rpx;
      height: 40rpx;
      background: url("https://ltjt.sjzballsportpark.com/statics/tyc/static/form-radio.png")
        no-repeat;
      background-size: 100% 100%;
      margin-right: 16rpx;

      &.active {
        background: url("https://ltjt.sjzballsportpark.com/statics/tyc/static/form-radio-active.png")
          no-repeat;
        background-size: 100% 100%;
      }
    }

    .radio-text {
      font-size: 32rpx;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.9);
      line-height: 44rpx;
    }
  }

  .btn-box {
    position: fixed;
    bottom: 0;
    background: #ffffff;
    width: calc(100% - 64rpx);
    height: 124rpx;
    box-sizing: content-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 32rpx;
    padding-left: 32rpx;
    box-shadow: 0rpx 14rpx 58rpx 0rpx rgba(100, 100, 111, 0.2);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .btn-cancel {
      width: 240rpx;
      height: 80rpx;
      background: #ffffff;
      border-radius: 44rpx 44rpx 44rpx 44rpx;
      opacity: 1;
      border: 2rpx solid rgba(0, 0, 0, 0.1);
      font-size: 28rpx;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.7);
      line-height: 80rpx;
      text-align: center;
    }

    .btn-confirm {
      width: 422rpx;
      height: 80rpx;
      background: #ff5000;
      border-radius: 44rpx 44rpx 44rpx 44rpx;
      font-size: 28rpx;
      font-weight: 500;
      color: #ffffff;
      line-height: 80rpx;
      text-align: center;
    }
  }
}
</style>
